<template>
  <view class="coupon-center">
    <!-- 兑换码区域 -->
    <view class="exchange-section">
      <view class="exchange-box">
        <view class="exchange-title">兑换码</view>
        <view class="exchange-input-box">
          <input
            class="exchange-input"
            type="text"
            v-model="exchangeCode"
            placeholder="请输入兑换码"
            maxlength="20"
            @confirm="handleExchange"
          />
          <button class="exchange-btn" @tap="handleExchange">兑换</button>
        </view>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view class="section-title">可领取优惠券</view>
      <view class="coupon-content">
        <view
          class="coupon-item"
          v-for="(coupon, index) in coupons"
          :key="index"
          @tap="viewCouponDetail(coupon)"
        >
          <view
            class="coupon-left"
            :class="{
              'discount-coupon': coupon.tag === '折扣券',
              'free-coupon': coupon.goodsType === 2
            }"
          >
            <view class="coupon-tag" v-if="coupon.goodsType !== undefined">
              {{ coupon.goodsType === 0 ? '全场通用' : (coupon.goodsType === 2 ? '指定商品' : '') }}
            </view>
            <view class="discount">
              <text class="amount">{{ formatAmount(coupon.discount) }}</text>
              <text class="unit">元</text>
            </view>
            <view class="condition" v-if="coupon.min > 0"
              >满{{ formatAmount(coupon.min) }}元可用</view
            >
            <view class="condition" v-else>无门槛使用</view>
          </view>
          <view class="coupon-right">
            <view class="coupon-info">
              <view class="coupon-name">{{ coupon.name }}</view>
              <view class="coupon-desc">{{ coupon.desc }}</view>
              <view class="coupon-time" v-if="!coupon.days"
                >{{ formatDate(coupon.startTime) }} -
                {{ formatDate(coupon.endTime) }}</view
              >
              <view class="coupon-time" v-else>
                有效期：{{ coupon.days }}天
              </view>
            </view>
            <view class="coupon-action">
              <button
                class="receive-btn"
                :disabled="coupon.userStatus !== 1"
                :class="{
                  'received': coupon.userStatus === 2,
                  'out-of-stock': coupon.userStatus === 3,
                  'expired': coupon.userStatus === 4,
                  'out': coupon.userStatus === 5
                }"
                @tap.stop="receiveCoupon(coupon)"
              >
                {{ 
                  coupon.userStatus === 1 ? '立即领取' : 
                  (coupon.userStatus === 2 ? '已领取' : 
                  (coupon.userStatus === 3 ? '数量不足' : 
                  (coupon.userStatus === 4 ? '已过期' : 
                  (coupon.userStatus === 5 ? '已下架' : '立即领取')))) 
                }}
              </button>
            </view>
          </view>
        </view>

        <!-- 无优惠券提示 -->
        <view class="empty-tip" v-if="coupons.length === 0">
          <image
            class="empty-icon"
            src="/static/images/common/empty.png"
          ></image>
          <view class="empty-text">暂无优惠券</view>
        </view>

        <!-- 加载更多提示 -->
        <view class="loading-more" v-if="coupons.length > 0">
          <text v-if="hasMore && !loadingMore">上拉加载更多</text>
          <text v-else-if="loadingMore">加载中...</text>
          <text v-else>没有更多了</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      coupons: [],
      exchangeCode: '', // 兑换码
      loading: false,
      page: 1, // 当前页码
      limit: 10, // 每页数量
      hasMore: true, // 是否有更多数据
      loadingMore: false, // 是否正在加载更多
      totalPages: 1, // 总页数
      needRefresh: false // 是否需要刷新数据
    }
  },
  onLoad() {
    this.loadData()
  },
  // 页面显示时检查是否需要刷新数据
  onShow() {
    // 如果设置了需要刷新的标志，则刷新数据
    if (this.needRefresh) {
      this.refreshData()
      this.needRefresh = false
    }
  },
  onPullDownRefresh() {
    this.refreshData()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 500)
  },
  // 添加页面滚动到底部事件
  onReachBottom() {
    this.loadMoreCoupons()
  },
  methods: {
    // 刷新数据
    refreshData() {
      this.page = 1
      this.hasMore = true
      this.coupons = []
      this.loadData()
    },

    // 加载更多数据
    loadMoreCoupons() {
      if (this.hasMore && !this.loadingMore) {
        this.page++
        this.loadData(true)
      }
    },

    // 加载数据
    async loadData(isLoadMore = false) {
      if (this.loading) return
      this.loading = true

      if (isLoadMore) {
        this.loadingMore = true
      } else {
        uni.showLoading({
          title: '加载中...'
        })
      }

      try {
        // 获取优惠券列表
        const res = await this.$get('coupon/list', {
          page: this.page,
          limit: this.limit
        })

        if (res.errno === 0) {
          const newCoupons = res.data.list || []

          // 更新总页数
          this.totalPages = res.data.pages || 1

          // 判断是否还有更多数据
          this.hasMore = this.page < this.totalPages

          // 追加或替换数据
          if (isLoadMore) {
            this.coupons = [...this.coupons, ...newCoupons]
          } else {
            this.coupons = newCoupons
          }
        } else {
          uni.showToast({
            title: res.errmsg || '获取优惠券失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        })
      } finally {
        if (isLoadMore) {
          this.loadingMore = false
        } else {
          uni.hideLoading()
        }
        this.loading = false
      }
    },

    // 领取优惠券
    receiveCoupon(coupon) {
      if (coupon.userStatus !== 1) return
      
      uni.showLoading({
        title: '领取中...'
      })
      
      this.$post('coupon/receive', {
        couponId: coupon.id
      })
        .then(res => {
          if (res.errno === 0) {
            uni.showToast({
              title: '领取成功',
              icon: 'success'
            })
            // 更新优惠券状态
            coupon.userStatus = 2
          } else {
            uni.showToast({
              title: res.errmsg || '领取失败',
              icon: 'none'
            })
          }
        })
        .catch(error => {
          console.error('领取优惠券失败', error)
          uni.showToast({
            title: '领取失败',
            icon: 'none'
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },

    // 查看优惠券详情
    viewCouponDetail(coupon) {
      uni.navigateTo({
        url: `/pages/coupon/center-detail?id=${coupon.id}&name=${encodeURIComponent(coupon.name)}&desc=${encodeURIComponent(coupon.desc)}&discount=${coupon.discount}&min=${coupon.min}&startTime=${encodeURIComponent(coupon.startTime)}&endTime=${encodeURIComponent(coupon.endTime)}&goodsType=${coupon.goodsType}&status=${coupon.userStatus}&tag=${encodeURIComponent(coupon.tag || '')}&days=${coupon.days || 0}`
      })
    },

    // 处理兑换码兑换
    async handleExchange() {
      if (!this.exchangeCode) {
        uni.showToast({
          title: '请输入兑换码',
          icon: 'none'
        })
        return
      }

      try {
        // 调用兑换接口
        const res = await this.$post('coupon/exchange', {
          code: this.exchangeCode
        })
        uni.hideLoading()

        if (res.errno === 0) {
          uni.showToast({
            title: '兑换成功',
            icon: 'none'
          })

          // 清空兑换码
          this.exchangeCode = ''
        } else {
          uni.showToast({
            title: res.errmsg || '兑换失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (err) {
        uni.hideLoading()
        uni.showToast({
          title: '兑换失败，请稍后再试',
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 格式化金额
    formatAmount(amount) {
      return amount.toFixed(2)
    },

    // 格式化折扣
    formatDiscount(discount) {
      return (discount / 10).toFixed(1)
    },

    // 格式化日期
    formatDate(dateStr) {
      // 处理iOS兼容性问题，将yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss
      if (dateStr) {
        // 替换横杠为斜杠，确保iOS设备可以正确解析
        dateStr = dateStr.replace(/-/g, '/')
      }
      const date = new Date(dateStr)
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '日期无效'
      }
      return `${date.getMonth() + 1}.${date.getDate()}`
    },

    // 页面跳转
    navigateTo(url) {
      uni.navigateTo({
        url
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/common/theme.scss';

.coupon-center {
  min-height: 100vh;
  background-color: $bg-main;
  padding-bottom: 30rpx;
  padding-top: 30rpx;
  display: flex;
  flex-direction: column;
}

.exchange-section {
  margin: 0 30rpx 30rpx;

  .exchange-box {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .exchange-title {
      font-size: 28rpx;
      font-weight: bold;
      color: $primary-dark-pink;
      margin-bottom: 16rpx;
    }

    .exchange-input-box {
      display: flex;
      align-items: center;

      .exchange-input {
        flex: 1;
        height: 80rpx;
        border: 1px solid #eee;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }

      .exchange-btn {
        width: 160rpx;
        height: 80rpx;
        margin-left: 20rpx;
        background-color: $gradient-button;
        color: #fff;
        font-size: 28rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 8rpx;

        &:disabled {
          background-color: #ccc;
        }
      }
    }
  }
}

.coupon-list {
  padding: 0 30rpx;
  flex: 1;
  display: flex;
  flex-direction: column;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: $primary-dark-pink;
    margin-bottom: 20rpx;
  }

  .coupon-content {
    flex: 1;
  }

  .coupon-item {
    display: flex;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .coupon-left {
      width: 220rpx;
      padding: 30rpx 20rpx;
      background-color: #b84a39;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 20rpx;
        background: radial-gradient(
          circle at left,
          transparent 10rpx,
          #fff 10rpx
        );
        background-size: 20rpx 20rpx;
        background-position: -10rpx 10rpx;
      }

      &.discount-coupon {
        background-color: #ff9500;
      }

      &.free-coupon {
        background-color: #5e35b1;
      }

      .coupon-tag {
        position: absolute;
        top: 0rpx;
        left: 0rpx;
        font-size: 16rpx;
        color: #fff;
        padding: 2rpx 6rpx;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 4rpx;
      }

      .discount {
        display: flex;
        align-items: baseline;

        .amount {
          font-size: 40rpx;
          font-weight: bold;
        }

        .unit {
          font-size: 28rpx;
          margin-left: 4rpx;
        }
      }

      .condition {
        font-size: 24rpx;
        margin-top: 10rpx;
        opacity: 0.9;
      }
    }

    .coupon-right {
      flex: 1;
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .coupon-info {
        flex: 1;

        .coupon-name {
          font-size: 30rpx;
          font-weight: bold;
          color: $primary-dark-pink;
          margin-bottom: 10rpx;
        }

        .coupon-desc {
          font-size: 24rpx;
          color: $primary-light-pink;
          margin-bottom: 10rpx;
        }

        .coupon-time {
          font-size: 22rpx;
          color: #999;
        }
      }

      .coupon-action {
        width: 140rpx;

        .receive-btn {
          width: 100%;
          height: 60rpx;
          line-height: 60rpx;
          font-size: 24rpx;
          color: #fff;
          background-color: $gradient-button;
          border-radius: 30rpx;
          padding: 0;

          &[disabled] {
            background-color: #ccc;
            color: #fff;
          }
          
          &.received {
            background-color: #ccc;
          }
          
          &.out-of-stock {
            background-color: #999;
          }
          
          &.expired {
            background-color: #999;
          }
          
          &.out {
            background-color: #999;
          }
        }
      }
    }
  }

  .empty-tip {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;

    .empty-icon {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .loading-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 24rpx;
  }
}
</style>
